<template>
  <div class="app-container">
    <div v-if="isSearchBtn" class="filter-container">
      <el-date-picker
        v-model="listQuery.time"
        type="datetimerange"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        align="right"
      />&nbsp;&nbsp;
      <el-input v-model="listQuery.title" placeholder="关键词" style="width: 200px;margin-right: 10px;" clearable @keyup.enter.native="handleFilter" />
      <el-button v-waves type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>

    </div>
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;height: 2.5rem;">
        <el-button v-show="isShowBtn" v-permission="'loginlog@del'" class="filter-item" type="danger" icon="el-icon-delete" @click="handleDeleteAll">
          批量删除
        </el-button>
        <el-button circle style="float: right;" icon="el-icon-download" @click="excelDownload" />
        <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @select-all="showDeleteBtn"
        @select="showDeleteSelectBtn"
      >
        <el-table-column
          align="center"
          type="selection"
        />
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <el-tooltip v-if="row.status=='error'" class="item" effect="dark" :content="row.error_message" placement="top">
              <el-tag
                type="danger"
                effect="dark"
              >
                失败
              </el-tag>
            </el-tooltip>
            <el-tag
              v-if="row.status=='success'"
              :type="row.status"
              effect="dark"
            >
              成功
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="登录IP">
          <template slot-scope="{row}">
            <span>{{ row.login_ip }}</span>
          </template>
        </el-table-column>
        <el-table-column label="IP归属">
          <template slot-scope="{row}">
            <span>{{ row.ip_address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户浏览器">
          <template slot-scope="{row}">
            <span>{{ row.browser_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="系统" class-name="status-col">
          <template slot-scope="{row}">
            <span>{{ row.system_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登录时间">
          <template slot-scope="{row}">
            <span>{{ row.created_at }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.p" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

  </div>
</template>

<script>
import { fetchList, delLog } from '@/api/login-log'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'PagePermission',
  components: { Pagination },
  directives: { waves, permission },
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      list: null,
      total: 0,
      listLoading: true,
      downloadLoading: false,
      listQuery: {
        p: 1,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id',
        time: ''
      },
      ps: '',
      isSearchBtn: false,
      dialogFormVisible: false,
      dialogStatus: '',
      isShowSwitch: '',
      ids: [],
      isShowBtn: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    showBtn() {
      if (this.isSearchBtn === false) {
        this.isSearchBtn = true
      } else {
        this.isSearchBtn = false
      }
    },
    excelDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['Id', '用户名', '浏览器类型', '系统类型', '登录IP', 'IP归属', '登录时间']
        const filterVal = ['id', 'username', 'browser_type', 'system_type', 'login_ip', 'ip_address', 'created_at']
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '登录记录',
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    showDeleteBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      if (this.ids.length > 0) {
        this.isShowBtn = true
      } else {
        this.isShowBtn = false
      }
    },
    showDeleteSelectBtn: function(selection, row) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      if (this.ids.length > 0) {
        this.isShowBtn = true
      } else {
        this.isShowBtn = false
      }
    },
    handleDeleteAll() {
      const data = {}
      data.ids = this.ids
      this.listLoading = true
      delLog(data).then(response => {
        this.ids = []
        this.getList()
        this.isShowBtn = false
        this.listLoading = false
        this.$message({
          message: response.message,
          type: 'success'
        })
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        title: undefined,
        is_hid: undefined,
        sort: '+id',
        time: ''
      }
      this.getList()
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style>
.filter-item{
  margin-right: 0.3125rem;
}
</style>
